const { url } = require('../../config/index.js') // 接口请求地址
const { getUserAddress, hasPassword, commonSuccess } = require('../../utils/util.js') // 获取地址, 是否有设置支付密码
const { time2 } = require('../../utils/format.js') // 格式化工具
const MD5 = require('../../utils/md5.js') // MD5

Page({
  // 页面的初始数据
  data: {
    shopData: {}, // 店铺信息
    payWay: 'weixin', // 支付方式
    hasAddress: true, // 有没有收货地址
    eatWay: 'there', // 堂食 外送
    userAddressList: [], // 用户地址列表
    nowAddress: null, // 当前选择地址
    payList: null, // 商品列表
    totalPay: null, // 总价
    payCanUseData: {}, // 支付用数据
    activity: false, // 买赠活动跳转过来的
    showCashBox: false, // 是否显示代金券box
    allVoucher: [], // 可用代金券
    chooseCashId: '', // 已选代金券的id
    cashNumber: 0, // 减免金额,
    pwd: '', // 支付密码
    showYuePay: false, // 显示余额支付
    isFocus: false, // 密码框焦点
    yueInfo: {}, // 余额支付数据
    inPay: false, // 是否正在支付中
    userAmount: 0, // 用户余额
    imgSrc: 'http://121.40.78.200/pic/servDetail/2adf8864-cdc9-4079-a029-1000020fd139.png'
  },
  // 获取代金券
  getCash(cashs) {
    wx.request({
      url: url + 'CashVolume/getMyCashVolList.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        TYPE: 1,
        USER_ID: wx.getStorageSync('userInfo').USER_ID,
        SECOND_CLASS: cashs,
        PAGE_NO: 1,
        PAGE_SIZE: 999
      },
      success: res => {
        console.log(res.data.RESULT_DATA)
        // 过滤不可用代金券
        this.filterVoucher(res.data.RESULT_DATA)
      }
    })
  },
  /*
   * 代金券选择
   * 
   */
  cashChoose(e) {
    // 计算最终优惠价格
    let VoucherMessage = e.currentTarget.dataset.item // 选择的代金券信息
    console.info(VoucherMessage)
    this.setData({ totalPay: this.data.payCanUseData.TOTAL_PRICE }) // 每次选优惠券，还原总价格
    let cashId = wx.getStorageSync('shopinfo').COMP_ID // 店铺id

    let orderMessage = this.data.payCanUseData // 处理后的总数据
    let shopList = orderMessage.ORDER_LIST[0].SERV_PARAMS // 处理后的商品列表

    //判断当前店是否开启了抵券功能 (0为通用券||店铺券)
    if (VoucherMessage.COMP_ID == 0 || VoucherMessage.COMP_ID == orderMessage.ORDER_LIST[0].COMP_ID) {
      //判断商品是否能使用券
      //SUPP_NORCASH_VOL满减券   SUPP_CASH_VOL N元券  SUPP_DIS_VOL折扣券

      console.log(VoucherMessage.USE_RANGE_IDS)

      //满减券
      let userRange = (VoucherMessage.USE_RANGE_IDS).split(",");
      if (VoucherMessage.CATEGORY == 1) {
        let sum = 0;
        for (let i = 0; i < shopList.length; i++) {
          if (shopList[i].SUPP_NORCASH_VOL == 1) {//满减券
            for (let m = 0; m < userRange.length; m++) {
              if (userRange[m] == shopList[i].FIRST_CLASS) {
                sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
              }
            }
          }
        }
        if (sum >= VoucherMessage.USABLE_PRICE) {
          this.setData({
            totalPay: this.data.totalPay - VoucherMessage.AMOUNT, // 最终支付价格
            cashNumber: VoucherMessage.AMOUNT, // 减免金额
            chooseCashId: VoucherMessage.CASH_VOL_NO // 代金券id
          })
        } else {
          this.setData({ chooseCashId: "" })
          wx.showModal({
            title: '提示',
            content: '此订单不能使用该代金券',
            showCancel: false
          })
        }
      } else if (VoucherMessage.CATEGORY == 3) {
        let sum = 0;
        for (let i = 0; i < shopList.length; i++) {
          if (shopList[i].SUPP_NORCASH_VOL == 1) {
            for (let m = 0; m < userRange.length; m++) {
              if (userRange[m] == shopList[i].SECON_CLASS) {
                sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
              }
            }
          }
        }
        if (sum >= VoucherMessage.USABLE_PRICE) {
          this.setData({
            totalPay: this.data.totalPay - VoucherMessage.AMOUNT, // 最终支付价格
            cashNumber: VoucherMessage.AMOUNT, // 减免金额
            chooseCashId: VoucherMessage.CASH_VOL_NO // 代金券id
          })
        } else {
          this.setData({ chooseCashId: "" })
          wx.showModal({
            title: '提示',
            content: '此订单不能使用该代金券',
            showCancel: false
          })
        }
      }
      //N元券
      else if (VoucherMessage.CATEGORY == 4) {
        let priceList = [];
        let max = 0;

        for (let i = 0; i < shopList.length; i++) {
          if (shopList[i].SUPP_CASH_VOL == 1) {
            console.log(shopList[i])
            for (let m = 0; m < userRange.length; m++) {
              if (userRange[m] == shopList[i].SECON_CLASS) {
                if (shopList[i].PRICE > max) {
                  max = shopList[i].PRICE;
                }
              }
            }
          }
        }
        if (max == 0) {
          this.setData({ chooseCashId: "" })
          wx.showModal({
            title: '提示',
            content: '此订单不能使用该代金券',
            showCancel: false
          })
        } else {
          console.log(this.data.totalPay)
          console.log(max)
          console.log(VoucherMessage.AMOUNT)
          this.setData({
            totalPay: this.data.totalPay - max + Number(VoucherMessage.AMOUNT), // 最终支付价格
            cashNumber: max - VoucherMessage.AMOUNT, // 减免金额 VoucherMessage.AMOUNT
            chooseCashId: VoucherMessage.CASH_VOL_NO // 代金券id
          })
        }
      }
      //折扣券
      else if (VoucherMessage.CATEGORY == 5) {
        let sum = 0;
        let noDisSum = 0;
        for (let i = 0; i < shopList.length; i++) {
          if (shopList[i].SUPP_DIS_VOL == 1) {//折扣券
            for (let m = 0; m < userRange.length; m++) {
              if (userRange[m] == shopList[i].SECON_CLASS) {
                sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
              }
            }
          } else {
            noDisSum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
          }
        }
        if (sum == 0) {
          this.setData({ chooseCashId: "" })
          wx.showModal({
            title: '提示',
            content: '此订单不能使用该代金券',
            showCancel: false
          })
        } else {
          this.setData({
            totalPay: (sum * Number(VoucherMessage.AMOUNT) + noDisSum).toFixed(2), // 最终支付价格
            cashNumber: (sum * (1 - Number(VoucherMessage.AMOUNT))).toFixed(2), // 减免金额
            chooseCashId: VoucherMessage.CASH_VOL_NO // 代金券id
          })
        }

      }
      //兑换券，兑换券只能选择userrage中和商品id对应的商品进行兑换，兑换是只需要支付一元
      else if (VoucherMessage.CATEGORY == 2) {
        let sum = 0;
        let duiPrice = 0;
        for (let i = 0; i < shopList.length; i++) {
          sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
          for (let m = 0; m < userRange.length; m++) {
            if (userRange[m] == shopList[i].SERV_ID) {
              //找到能兑换的商品后，并把单价存放在duiPrice中
              duiPrice = shopList[i].PRICE;
            }
          }

        }
        if (duiPrice == 0) {
          this.setData({ chooseCashId: "" })
          wx.showModal({
            title: '提示',
            content: '此订单不能使用该代金券',
            showCancel: false
          })
        } else {
          //如果可以使用兑换券就简单可以兑换商品的单价（兑换券只能兑换一件商品）;
          this.setData({
            totalPay: sum - duiPrice, // 最终支付价格
            cashNumber: duiPrice, // 减免金额
            chooseCashId: VoucherMessage.CASH_VOL_NO // 代金券id
          })
        }
      }
      else {
        this.setData({ chooseCashId: "" })
        wx.showModal({
          title: '提示',
          content: '此订单不能使用该代金券',
          showCancel: false
        })
      }
    }
    console.warn(this.data.cashNumber)
    // 关闭代金券选择
    this.setData({ showCashBox: false })
  },

  /* 
   * 过滤不可用代金券（该部分来自咖啡M站，代码稍做修改）
  */

  filterVoucher(arr) {
    let allVoucher = [] // 存放过滤后代金券
    let orderMessage = this.data.payCanUseData // 处理后的总数据
    let shopList = orderMessage.ORDER_LIST[0].SERV_PARAMS // 处理后的商品列表

    for (let i = 0; i < arr.length; i++) {
      let VoucherMessage = arr[i] // 代金券



      //判断当前店是否开启了抵券功能 -- （如compId为0，则适用范围通用 || 为当前店铺专用券）
      if (VoucherMessage.COMP_ID == 0 || VoucherMessage.COMP_ID == orderMessage.ORDER_LIST[0].COMP_ID) {
        //判断商品是否能使用券
        //SUPP_NORCASH_VOL满减券   SUPP_CASH_VOL N元券  SUPP_DIS_VOL折扣券
        //满减券
        let userRange = (VoucherMessage.USE_RANGE_IDS).split(",");

        // 适用范围ID
        // console.log(userRange)

        // 大类满抵券（category=1）
        if (VoucherMessage.CATEGORY == 1) {

          let sum = 0;
          for (let i = 0; i < shopList.length; i++) {
            if (shopList[i].SUPP_NORCASH_VOL == 1) {
              for (let m = 0; m < userRange.length; m++) {
                if (userRange[m] == shopList[i].FIRST_CLASS) {
                  sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
                }
              }
            }
          }
          if (sum >= VoucherMessage.USABLE_PRICE) {
            //满足条件的代金券存储到数组中
            allVoucher.push(arr[i]);
          } else {
          }
          // “小类满抵券(category=3)”：除了以商品/服务的二级分类做为标识外，其余与“大类满减券一致”。
        } else if (VoucherMessage.CATEGORY == 3) {
          let sum = 0;
          for (let i = 0; i < shopList.length; i++) {
            if (shopList[i].SUPP_NORCASH_VOL == 1) {
              for (let m = 0; m < userRange.length; m++) {
                if (userRange[m] == shopList[i].SECON_CLASS) {
                  sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
                }
              }
            }
          }
          if (sum >= VoucherMessage.USABLE_PRICE) {
            allVoucher.push(arr[i]);
          }
        }
        // N元券(category=4)：以商品/服务的二级分类为匹配标识，当商品/服务的SUPP_CASH_VOL为1时则可以使用（只需要支付代金券的AMOUNT金额即刻完成下单
        else if (VoucherMessage.CATEGORY == 4) {

          let priceList = [];
          let max = 0;
          console.warn(shopList)

          for (let i = 0; i < shopList.length; i++) {
            if (shopList[i].SUPP_CASH_VOL == 1) {

              for (let m = 0; m < userRange.length; m++) {
                if (userRange[m] == shopList[i].SECON_CLASS) {
                  if (shopList[i].PRICE > max) {
                    max = shopList[i].PRICE;
                  }
                }
              }
            }
          }
          if (max == 0) {

          } else {
            allVoucher.push(arr[i]);
          }
        }
        //折扣券(category=5)
        else if (VoucherMessage.CATEGORY == 5) {
          console.log(VoucherMessage.CATEGORY)

          console.warn(shopList)
          // console.log(shopList) 商品列表
          let sum = 0;
          let noDisSum = 0;
          for (let i = 0; i < shopList.length; i++) {
            if (shopList[i].SUPP_DIS_VOL == 1) { // 若该商品支持折扣券
              for (let m = 0; m < userRange.length; m++) { // userRange 可用品类id
                if (userRange[m] == shopList[i].SECON_CLASS) { // 商品二级分类 在 可用品类id中
                  sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
                }
              }
            } else {
              noDisSum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
            }
          }

          if (sum == 0) {

          } else {
            allVoucher.push(arr[i]);
          }

        }
        //兑换券，兑换券只能选择userrage中和商品id对应的商品进行兑换，兑换是只需要支付一元
        else if (VoucherMessage.CATEGORY == 2) {
          let sum = 0;
          let duiPrice = 0;
          for (let i = 0; i < shopList.length; i++) {
            sum += Number(shopList[i].PRICE) * Number(shopList[i].QUANTITY);
            for (let m = 0; m < userRange.length; m++) {
              if (userRange[m] == shopList[i].SERV_ID) {
                //找到能兑换的商品后，并把单价存放在duiPrice中
                duiPrice = shopList[i].PRICE;
              }
            }
          }
          if (duiPrice == 0) {

          } else {
            //如果可以使用兑换券就简单可以兑换商品的单价（兑换券只能兑换一件商品）;
            allVoucher.push(arr[i]);
          }
        }
      }
    }
    // 可用代金券
    console.log(allVoucher)
    allVoucher.forEach((e, i) => { // 到期时间格式化（小程序无过滤器需单独处理）
      e.filterTime = time2(e.EXP_DATE)
    })
    this.setData({ allVoucher: allVoucher }) // 可用代金券
  },
  beforePay () {
    if (this.data.inPay) {
      return
    }
    this.setData({ inPay: true })
    console.log('正在支付中')
    if (this.data.payWay !== 'weixin') {
      hasPassword(wx.getStorageSync('userInfo').USER_ID)
      .then(res => {
        console.log(res)
        if (res.STATUS_CODE == 1) {
          if (res.PAY_PASSWORD_STATUS == 1){ // 设置过密码
            this.addressCheack()
          } else {
            // 没有密码
            
            wx.redirectTo({
              url: '/pages/validatePhone/validatePhone'
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.RESULT_MSG,
            showCancel: false
          })
          this.setData({ inPay: false })
        }
      })
      .catch(err => {
        console.error(err)
        this.setData({ inPay: false })
      })
    } else {
      this.addressCheack()
    }
  },
  addressCheack () {
    // if(this.data.inPay) {
    //   return
    // }
    // this.setData({ inPay: true })
    // console.log('正在支付中')
    if (this.data.eatWay !== 'there'){
      // 收货地址距离检测
      wx.request({
        url: url + 'ServShop/getReceivingDistance.action',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          ADDRESS_ID: this.data.nowAddress.ADR_ID
        },
        success: (res) => {
          console.log(res)
          let d = res.data
          if (res.data.STATUS_CODE == 1) {
            if (res.data.DISTRIBUTION == 0){
              this.setData({ inPay: false })
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: '不在配送范围内',
              })
            } else {
              this.mulitOrderPay()
            }
          } else {
            this.setData({ inPay: false })
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: d.RESULT_MSG,
            })
          }
        }
      })
    } else {
      this.mulitOrderPay()
    }
  },
  // 支付1 (多订单合并支付)
  mulitOrderPay () {
    
    let payWay = this.data.payWay
    // 支付数据
    let shopOrderMess = this.data.payCanUseData

    shopOrderMess.PAY_WAY = payWay === 'weixin' ? 2 : 9 // 支付方式： 2 微信支付 9 余额支付
    if (this.data.chooseCashId == '') { // 未选择代金券
      shopOrderMess.ORDER_LIST[0].CASH_VOL_NO = '';
    } else {
      shopOrderMess.ORDER_LIST[0].CASH_VOL_NO = this.data.chooseCashId //代金券编号
    }
    if (this.data.eatWay == 'takeAway') { // 如果是外送单 添加联系信息
      shopOrderMess.MOBILE_PHONE = this.data.nowAddress.PHONE;//联系人号码
      shopOrderMess.ADR_ID = this.data.nowAddress.ADR_ID; //地址编号
      shopOrderMess.CONTACT = this.data.nowAddress.CONTACT; //地址编号
    }
    // console.error(shopOrderMess)
    // return

    // 多订单合并支付接口
    wx.request({
      url: url + 'ServOrderNew/createMulitOrder.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        jsonParams: JSON.stringify(shopOrderMess)
      },
      success: res => {
        console.log(res.data)
        if (res.data.STATUS_CODE == 1) {
          // 微信支付
          if (payWay === 'weixin') {
            this.WXunitePay(res.data.TRADE_NO, res.data.TOTAL_FEE, res.data.BODY, res.data.ORDER_NO);
          // 余额支付
          } else {
            let yueInfo = {
              TRADE_NO: res.data.TRADE_NO,
              TOTAL_FEE: res.data.TOTAL_FEE,
              USER_ID: res.data.USER_ID
            }
            this.setData({
              yueInfo: yueInfo
            })
            this.YuEPay()
          }
        } else if (res.data.STATUS_CODE == 20) {
          this.setData({ inPay: false })
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '今日代金券使用已经超过使用次数'
          })
        } else {
          this.setData({ inPay: false })
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.RESULT_MSG
          })
        }
      }
    })    
  },
  // 微信支付2
  WXunitePay(TRADE_NO, TOTAL_FEE, BODY, ORDER_NO){
    console.log(arguments)
    // 微信支付接口
    wx.request({
      url: url + 'WXPay/getOrder.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        OPEN_ID: wx.getStorageSync('userInfo').AUTH_INFO.openid,
        TRADE_NO: TRADE_NO,
        TOTAL_FEE: TOTAL_FEE,
        BODY: BODY,
        ISAPP: 1 // 小程序支付标记
      },
      success: res => {
        console.log(res.data)
        if (res.data.STATUS_CODE == 1) {
          // 最后一步 微信支付api
          let that = this
          wx.requestPayment({
            'timeStamp': res.data.timestamp,
            'nonceStr': res.data.noncestr,
            'package': 'prepay_id=' + res.data.prepayid,
            'signType': 'MD5',
            'paySign': res.data.sign,
            'success': function (res) {
              // console.log(res)
              // 支付成功 删除支付数据
              wx.removeStorageSync('readyPayInfo') // 普通商品信息
              wx.removeStorageSync('activity2to1') // 活动商品信息
              // 成功跳转
              // console.log(this)
              that.commonSuccess()
            },
            'fail': function (res) {
              console.log(res)
              that.setData({ inPay: false })
              // wx.showModal({
              //   title: '提示',
              //   showCancel: false,
              //   content: '支付失败'
              // })
              wx.redirectTo({
                url: '/pages/myOrder/myOrder',
              })
            }
          })
        }
      },
      fail: err => {
        this.setData({ inPay: false })
      }
    })   
  },
  closeYuePay () {
    // this.inpNoFocus()
    wx.redirectTo({
      url: '/pages/myOrder/myOrder',
    })
    this.setData({
      inPay: false,
      showYuePay: false,
      pwd: ''
    })
  },
  // 支付密码输入
  pwdInput(e) {
    // console.log(e)
    let pwd = e.detail.value
    this.setData({
      pwd: pwd
    })
    // 输入6位 直接去支付
    if (pwd.length == 6) {
      // console.log(1231233)
      this.YueToPay()
    }
  },
  // 密码框获得焦点
  inpFocus() {
    // console.log(123)
    // if (this.data.isFocus) return 
    this.setData({
      isFocus: true
    })
  },
  // 余额支付1
  YuEPay(TRADE_NO, TOTAL_FEE, USER_ID) {
    this.setData({ // 显示密码框
      showYuePay: true
    })
    this.inpFocus() // input 自动聚焦
  },
  // 确认余额支付2
  YueToPay() {
    // 密码是否完整
    if (this.data.pwd.length < 6){
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请输入完整密码'
      })
      this.setData({ inPay: false })
      return
    }
    // 余额是否足够

    if (Number(this.data.userAmount) < Number(this.data.totalPay)){
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '余额不足'
      })
      this.setData({ inPay: false })
      return
    }
    let that = this
    wx.request({
      url: url + 'ServOrderNew/pospalNotifyAndUpdateServOrder.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        USER_ID: this.data.yueInfo.USER_ID,
        TRADE_NO: this.data.yueInfo.TRADE_NO,
        PASS_WORD: MD5(this.data.pwd)
      },
      success: res => {
        
        console.log(res.data)
        if (res.data.STATUS_CODE == 1) {
          // 支付成功删除支付信息
          wx.removeStorageSync('readyPayInfo') // 普通商品信息
          wx.removeStorageSync('activity2to1') // 活动商品信息
          // 成功跳转
          this.commonSuccess()
        } else {
          this.setData({ inPay: false })
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '支付失败 ' + res.data.RESULT_MSG
          })
        }
      },
      fail: err => {
        that.setData({ inPay: false })
        wx.redirectTo({
          url: '/pages/myOrder/myOrder',
        })
      }
    })  
  },
  // 成功跳转
  commonSuccess () {
    commonSuccess()
  },
  // 打开代金券选择
  cashClick (e) {
    // console.info(e)
    if (this.data.allVoucher.length == 0) return // 无可用代金券
    this.setData({ showCashBox: true})
  },
  // 不使用代金券
  noUseCash () {
    this.setData({ 
      chooseCashId: '', // 清空优惠券id
      showCashBox: false,
      totalPay: Number(wx.getStorageSync('readyPayInfo').totalPay) // 还原价格
    })
  },

  // 切换就餐方式
  changeWay (e) {
    let eatWay = e.currentTarget.dataset.way
    this.setData({ eatWay: eatWay })
  },
  // 新增地址或切换地址
  addOrChangeAddress () {
    let len = this.data.userAddressList.length
    // 有收货地址 -> 去切换地址 传参 way=my 从个人中心进入， way=choose 从选择收货地址进入
    if (len) {
      wx.navigateTo({
        url: '/pages/address/address?way=choose'
      })
    // 没有收货地址 -> 去新增地址 传参 way=new 新增， way=edit 编辑
    } else { 
      wx.navigateTo({
        url: '/pages/addAddress/addAddress?way=new'
      })
    }
  },
  // 地图
  shopInMap () {
    let info = wx.getStorageSync('shopinfo')
    wx.openLocation({
      name: info.SHOP_NAME,
      address: info.ADDRESS,
      latitude: Number(info.LATITUDE),
      longitude: Number(info.LONGITUDE),
      scale: 28
    })
  },
  // 去充值
  recharge () {
    wx.redirectTo({
      url: '/pages/recharge/recharge'
    })
  },
  // 支付方式切换
  thisWayPay (e) {
    let payWay = e.currentTarget.dataset.way
    console.info(payWay)
    // 余额不足不能选择余额支付
    if (payWay == 'yue' && (Number(this.data.userAmount) < Number(this.data.totalPay))) {
      return
    }
    this.setData({ payWay: payWay})
  },
  // 获取收货地址
  getAddress () {
    let userId = wx.getStorageSync('userInfo')
    // console.info(userId)
    // console.error(1)
    getUserAddress(userId.USER_ID)
      .then(res => {
        // console.log(res)
        this.setData({ userAddressList: res })

        // 查找是否存有已选地址id - 选择对应地址显示
        let addId = wx.getStorageSync('addressId')
        console.log(addId)
        if (addId) {
          res.forEach((e, i) => {
            if (e.ADR_ID == addId) {
              this.setData({
                nowAddress: e,
                eatWay: 'takeAway'
              })
              return
            }
          })
          wx.removeStorageSync('addressId')
        } else {
          // 没有已选地址id - 选择默认地址显示
          res.forEach((e, i) => {
            if (e.IS_DEFAULT == 1) {
              this.setData({ nowAddress: e })
              return
            }
          })
        }

      })
  },
  // 获取上一步商品信息（店铺入口）
  getUpGoods () {
    let shop_data = wx.getStorageSync('shopinfo')
    let info = wx.getStorageSync('readyPayInfo')
    this.setData({ 
      shopData: shop_data, // 商店信息
      payList: info.payInfo, // 商品列表
      totalPay: Number(info.totalPay) // 总价
    })
    // console.log(info)

    // 处理上一步信息 （支付用）↓
    let payCanUseData = {} // 最终支付数据
    payCanUseData.USER_ID = wx.getStorageSync('userInfo').USER_ID
    payCanUseData.PAY_WAY = ''; // 支付方式
    payCanUseData.ORDER_LIST = [{
      COMP_ID: wx.getStorageSync('shopinfo').COMP_ID, // 店铺
      CASH_VOL_NO: '', // 代金券编号
      SERV_PARAMS: [] // 商品信息
    }];
    // 放入总价
    payCanUseData.TOTAL_PRICE = info.totalPay; // 总价
    payCanUseData.SHOP_NAME = wx.getStorageSync('shopinfo').SHOP_NAME; // 店名
    for (let f in info.payInfo) { // 循环订单
      let singleGoodsData = {} // 容器
      singleGoodsData.SERV_ID = info.payInfo[f].SERV_ID // id
      singleGoodsData.QUANTITY = info.payInfo[f].countForCar // 数量
      singleGoodsData.PRICE = info.payInfo[f].PRICE // 价格
      singleGoodsData.FIRST_CLASS = info.payInfo[f].SERV_FIRST_CLASS // 一级分类id
      singleGoodsData.SECON_CLASS = info.payInfo[f].SERV_SECON_CLASS // 二级分类id
      singleGoodsData.SUPP_CASH_VOL = info.payInfo[f].SUPP_CASH_VOL // 是否支持代金券相关
      singleGoodsData.SUPP_DIS_VOL = info.payInfo[f].SUPP_DIS_VOL
      singleGoodsData.COMMENT_SIZE = info.payInfo[f].COMMENT_SIZE // 评论相关
      singleGoodsData.COMMENT_AVG = info.payInfo[f].COMMENT_AVG
      singleGoodsData.SUPP_NORCASH_VOL = info.payInfo[f].SUPP_NORCASH_VOL
      // console.log(singleGoodsData)
      // console.log(info.payInfo[f])
      // 存在多规格名和对规格选项
      if (info.payInfo[f]._name_ && info.payInfo[f].ATTR_LIST.length) {
        // 分割拿规格索引
        let key = f.split('$')
        singleGoodsData.ATTR_LIS = []; // 多规格数组
        // 遍历属性
        for (let i = 1; i < key.length; i++) {
          let noName = {};
          noName.TYPE = info.payInfo[f].ATTR_LIST[i - 1].TYPE;// 分类类型
          noName.ATTRIBURE = key[i]// 分类ID
          singleGoodsData.ATTR_LIS.push(noName);
          // console.error(noName)
        }
        // console.warn('最终')
        // console.warn(singleGoodsData)
        
      }

      payCanUseData.ORDER_LIST[0].SERV_PARAMS.push(singleGoodsData);
      
    }
    console.warn('payCanUseData')
    console.warn(JSON.stringify(payCanUseData))
    this.setData({ payCanUseData: payCanUseData })
      
    // 处理上一步信息 ↑
    // 代金券相关
    let cash = []
    for (let x in info.payInfo) {
      if (cash.indexOf(info.payInfo[x].SERV_SECON_CLASS) < 0){
        cash.unshift(info.payInfo[x].SERV_SECON_CLASS)
      }
    }
    let cashs = cash.sort().join(',') + ',10008'
    // console.log(cashs)
    this.getCash(cashs)
  },
  // 获取上一步商品信息（活动入口 买二送一 ， 买一送一，不可使用代金券）
  getUpGoodsAct () {
    let shop_data = wx.getStorageSync('shopinfo')
    let info = wx.getStorageSync('activity2to1') // 商品信息
    let actFor = [{
      SERV_SUBJECT: info.totalName,
        countForCar: 1,
        PRICE: info.totalPrice
      }]
    this.setData({
      shopData: shop_data, // 商店信息
      payList: actFor, // 商品列表
      totalPay: info.totalPrice // 总价
    })
    // 处理上一步信息 （支付用）↓
    let payCanUseData = {} // 最终支付数据
    payCanUseData.USER_ID = wx.getStorageSync('userInfo').USER_ID
    payCanUseData.ACT_ID = info.CAFE_ACTIVITY_ID // 活动id
    payCanUseData.PAY_WAY = '' // 支付方式
    payCanUseData.ACT_TYPE = info.actType // 订单活动类型
    payCanUseData.ORDER_LIST = [{
      COMP_ID: wx.getStorageSync('shopinfo').COMP_ID, // 店铺
      CASH_VOL_NO: '', // 代金券编号
      SERV_PARAMS: [] // 商品信息
    }];
    // 放入总价
    payCanUseData.TOTAL_PRICE = info.totalPrice; // 总价
    payCanUseData.SHOP_NAME = wx.getStorageSync('shopinfo').SHOP_NAME; // 店名
    // 循环放入商品
    for( let a = 0; a < info.swiperIndex.length; a++ ) {
      let singleGoodsData = {}
      singleGoodsData.SERV_ID = info.mealData[a][info.swiperIndex[a]].SERV_ID // id
      singleGoodsData.QUANTITY = 1 // 数量 1
      singleGoodsData.PRICE = info.mealData[a][info.swiperIndex[a]].PRICE // 价格
      singleGoodsData.FIRST_CLASS = info.mealData[a][info.swiperIndex[a]].SERV_FIRST_CLASS // 一级分类id
      singleGoodsData.SECON_CLASS = info.mealData[a][info.swiperIndex[a]].SERV_SECON_CLASS // 二级分类id
      singleGoodsData.SUPP_CASH_VOL = info.mealData[a][info.swiperIndex[a]].SUPP_CASH_VOL // 是否支持代金券相关
      singleGoodsData.SUPP_DIS_VOL = info.mealData[a][info.swiperIndex[a]].SUPP_DIS_VOL
      singleGoodsData.COMMENT_SIZE = info.mealData[a][info.swiperIndex[a]].COMMENT_SIZE // 评论相关
      singleGoodsData.COMMENT_AVG = info.mealData[a][info.swiperIndex[a]].COMMENT_AVG
      singleGoodsData.SUPP_NORCASH_VOL = info.mealData[a][info.swiperIndex[a]].SUPP_NORCASH_VOL
      singleGoodsData.CUP_NUM = a == 0 ? 1 : a == 1 ? 2 : a == 2 ? 3 : '' // 咖啡活动第几杯标识
      // 添加多规格信息
      if (info.multiOptions[a]) {
        singleGoodsData.ATTR_LIS = info.multiOptions[a]
      }
      payCanUseData.ORDER_LIST[0].SERV_PARAMS.push(singleGoodsData);
    }
    console.warn('payCanUseData')
    console.warn(JSON.stringify(payCanUseData))
    this.setData({ payCanUseData: payCanUseData })
    
  },

  // 获取用户余额
  getUserAmount () {
    wx.request({
      url: url + 'pospal/getPospalUserInfo.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        USER_ID: wx.getStorageSync('userInfo').USER_ID
      },
      success: res => {
        if (res.data.STATUS_CODE == 1) {
          let amount = res.data.AMOUNT
          this.setData({ userAmount: Number(amount) })
        }
      }
    }) 
  },
  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    if (options.type == 'activity') { // 买赠
      this.setData({ activity: true })
      this.getUpGoodsAct()
    } else {
      this.getUpGoods()
    }
    // 获取用户余额
    this.getUserAmount()
  },
  // 生命周期函数--监听页面初次渲染完成
  onReady: function () {
  },
  // 生命周期函数--监听页面显示
  onShow: function () {
    // （选择地址回来）或（第一次进入）获取收货地址
    this.getAddress()
  },
  // 生命周期函数--监听页面隐藏
  onHide: function () {
  },
  // 生命周期函数--监听页面卸载
  onUnload: function () {
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
  },
  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
  },
  // 用户点击右上角转发
  onShareAppMessage: function () {
  },
  // 页面滚动触发事件的处理函数
  onPageScroll: function () {
  },
  // 当前是 tab 页时，点击 tab 时触发
  onTabItemTap () {
  }
})
